package com.wwz.datasource.aop;

import com.wwz.datasource.annotation.DS;
import com.wwz.datasource.config.DynamicDataSourceContextHolder;
import com.wwz.datasource.constants.DataSourceConstants;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * 切面
 */
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Pointcut("@within(org.springframework.stereotype.Service)")
    public void dataSourcePointCut() {
    }

    ;

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Class<?> aClass = null;
        try {
            aClass = Class.forName(signature.getDeclaringType().getName());

            if (aClass != null) {
                if (signature.getMethod().isAnnotationPresent(DS.class)) {
                    DynamicDataSourceContextHolder.setContextKey(signature.getMethod().getAnnotation(DS.class).value());
                } else if (aClass.isAnnotationPresent(DS.class)) {
                    DynamicDataSourceContextHolder.setContextKey(aClass.getAnnotation(DS.class).value());
                } else {
                    DynamicDataSourceContextHolder.setContextKey(DataSourceConstants.DS_KEY_MASTER);
                }
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            return point.proceed();
        } finally {
            DynamicDataSourceContextHolder.removeContextKey();
        }
    }
}